package com.qianfeng.smsplatform.apigateway.filters;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.smsplatform.apigateway.cache.ApiMappingCache;
import com.qianfeng.smsplatform.apigateway.pojo.TApiMapping;
import com.qianfeng.smsplatform.common.constants.InterfaceExceptionDict;
import com.qianfeng.smsplatform.common.dto.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by Jackiechan on 2022/3/9 21:29
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class RouttingFilter extends ZuulFilter {

    private ApiMappingCache apiMappingCache;

    @Autowired
    public void setApiMappingCache(ApiMappingCache apiMappingCache) {
        this.apiMappingCache = apiMappingCache;
    }
    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        //前面的过滤器可能会拦截请求,这里需要对请求进行判断,如果拦截了,就不执行下面的run
        RequestContext currentContext = RequestContext.getCurrentContext();
        return currentContext.sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String method = request.getParameter("method");//用户想要请求的服务
        TApiMapping tApiMapping = apiMappingCache.get(method);//获取到一个映射对象
        if (tApiMapping == null) {
            //没有
            currentContext.setSendZuulResponse(false);
//            currentContext.setResponseBody("没有找到服务");
//            currentContext.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
            currentContext.addZuulResponseHeader("content-Type", "application/json;charset=utf-8");
            R error = R.error(InterfaceExceptionDict.SERVICE_NOT_FOUND, "请求服务不存在");
            try {
                String resultJson = objectMapper.writeValueAsString(error);
                currentContext.setResponseBody(resultJson);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else{
            String serviceId = tApiMapping.getServiceId();
            String insideApiUrl = tApiMapping.getInsideApiUrl();
            currentContext.set(FilterConstants.SERVICE_ID_KEY, serviceId);
            System.err.println("替换前的地址是:" + insideApiUrl);
            Enumeration<String> parameterNames = request.getParameterNames();//获取到所有的参数名
            while (parameterNames.hasMoreElements()) {
                String pName = parameterNames.nextElement();//获取到每一个传递的参数的名字
                String value = request.getParameter(pName);//当前参数的值
                //给当前参数前后拼接{},然后从insideApiUrl替换掉这个拼接的数据,替换为value
                //如果当前参数不在占位符中,则不会替换
                // /{id}
                insideApiUrl = insideApiUrl.replace("{" + pName + "}", value);

            }
            System.err.println("替换后的地址是:" + insideApiUrl);
            currentContext.set(FilterConstants.REQUEST_URI_KEY, insideApiUrl);
        }


        return null;
    }
}
